package com.yx.learn.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.yx.learn.dao.UserDao;
import com.yx.learn.domain.User;

@Repository("userDao")
public class UserDaoImpl implements UserDao {
	
	@Autowired
	@Qualifier("hibernateTemplate")
	private HibernateTemplate hibernateTemplate;

	//通过用户账号密码查找用户
	public User findByNoPwd(String employNo, String password) throws Exception {
		// TODO Auto-generated method stub
		String hql = "From User where employNo= ? and password= ?";
		@SuppressWarnings("unchecked")
		List<User> list = (List<User>) hibernateTemplate.find(hql,
				new Object[] { employNo, password });
		return list.isEmpty() ? null : list.get(0);
	}
	
	public void saveUser(User user) throws Exception {
		hibernateTemplate.save(user);
	}

	public void deleteUser(User user) throws Exception {
		hibernateTemplate.delete(user);
	}

	public void updateUser(User user) throws Exception {
		//hibernateTemplate.update(user);
		hibernateTemplate.merge(user);
	}

	public User findById(int id) throws Exception {
		String queryString = "From User where id= ?";
		User user = (User) hibernateTemplate.find(queryString,
				new Object[] { id }).get(0);
		return user;
	}

	@SuppressWarnings("unchecked")
	public User findUserByNo(String employNo) throws Exception {
		String queryString = "From User where employNo= ?";
		List<User> list = (List<User>) hibernateTemplate.find(queryString,
				new Object[] { employNo });
		return list.isEmpty() ? null : list.get(0);
	}

	@SuppressWarnings("unchecked")
	public int findRows(String hql) throws Exception {
		List<User> allUser = hibernateTemplate.find(hql);
		return allUser.size();
	}

	@SuppressWarnings("unchecked")
	public List<User> findUsers(String hql, int pageNumber, int pageSize)
			throws Exception {

		Query query = hibernateTemplate.getSessionFactory().getCurrentSession().createQuery(hql);
System.out.println("==========================================================="+query.list().size()+"pageNumber"+pageNumber+"pageSize"+pageSize);
		query.setFirstResult((pageNumber - 1) * pageSize);
		query.setMaxResults(pageSize);
		List<User> users = query.list();
		return users;
	}

	@SuppressWarnings("unchecked")
	public List<User> findAllUser(String hql) throws Exception {

		List<User> allUser = hibernateTemplate.find(hql);
		return allUser;
	}

	@SuppressWarnings("unchecked")
	public List<User> getUsers() throws Exception {
		// TODO Auto-generated method stub
		return this.hibernateTemplate.find("From User");
	}


}
